/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.model.command;

import org.eclipse.gef.commands.Command;
import org.eclipse.uml2.uml.Comment;

/**
 * Command to change the Body of a Comment.
 * 
 * @author frankd@ifi.uio.no
 */
public class SetCommentBodyCommand extends Command {

	private Comment comment;
	private String newBody, oldBody;

	public SetCommentBodyCommand() {
	}

	public SetCommentBodyCommand(final Comment comment, final String body) {
		setComment(comment);
		setBody(body);
	}

	public void setComment(final Comment comment) {
		this.comment = comment;
	}

	public void setBody(final String body) {
		if (body != null) {
			// Normalize all occurrences of \r\n with \n
			// because \r\n is translated into two newlines
			// in JDK 1.5 we could just write
			// this.newBody = body.replace("\r\n", "\n");
			// but replace is not available in JDK 1.4
			StringBuffer tmp = new StringBuffer(body.length());
			int i = 0;
			while (i < body.length()) {
				if (!(body.charAt(i) == '\r' && i + 1 < body.length() && body
						.charAt(i + 1) == '\n'))
					tmp.append(body.charAt(i));
				i++;
			}
			this.newBody = tmp.toString();
		} else
			this.newBody = null;
	}

	@Override
	public void execute() {
		if (comment != null) {
			oldBody = comment.getBody();
			comment.setBody(newBody);
		}
	}

	@Override
	public void undo() {
		if (comment != null) {
			comment.setBody(oldBody);
			oldBody = null;
		}
	}

	@Override
	public void redo() {
		this.execute();
	}

	@Override
	public void dispose() {
		comment = null;
		newBody = null;
		oldBody = null;
	}
}
